import { Component, ChangeDetectionStrategy } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { HttpHeaders } from '@angular/common/http';

const BIG_IMAGES = [
  `assets/img-big/bg5.jpeg`,
  `assets/img-big/bg6.jpeg`,
  `assets/img-big/bg7.jpeg`,
  `assets/img-big/bg1.jpg`,
  `assets/img-big/bg2.jpg`,
];

@Component({
  selector: 'account-forget',
  templateUrl: './forget.component.html',
  host: {
    '[class.account-container]': 'true',

    '[style.height]': `'100%'`,
    '[style.background-image]': `'url(' + bigImage + ')'`,
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ForgetComponent {
  // tslint:disable-next-line: no-bitwise
  bigImage = BIG_IMAGES[(Math.random() * BIG_IMAGES.length) | 0];
  type = 0;
  findMobile: FormGroup;
  stop = false;
  loading = false;
  constructor(public http: _HttpClient, fb: FormBuilder, private msg: NzMessageService) {
    this.findMobile = fb.group({
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
    });
  }

  get mobile() {
    return this.findMobile.controls.mobile;
  }

  sendCaptcha(e) {
    this.http
      .get(`/cf/admin/mobile/${this.findMobile.value.mobile}?_allow_anonymous=true&oper=重置密码`)
      .subscribe(res => {
        if (res.status !== 200) {
          e.cancel();
        }
      });
  }

  submit() {
    const params = {
      mobile: `SMS@${this.findMobile.value.mobile}`,
      code: `${this.findMobile.value.captcha}`,
    };
    const header = new HttpHeaders({
      tenant_id: '1',
      Authorization: 'Basic Y2Y6Y2xvdWQtZnJhbWV3b3Jr',
    });
    this.loading = true;
    this.http
      .post(`/cf/auth/mobile/token/sms?_allow_anonymous=true`, null, params, {
        headers: header,
      })
      .subscribe(res => {
        this.loading = false;
        this.msg.success('账号密码已重置为1111');
        this.findMobile.reset();
      });
  }
}
